class Setting < ActiveRecord::Base

  has_many :setting_usages, :dependent => :destroy
  has_many :buckets, :through => :setting_usages
  has_many :setting_overrides, :dependent => :destroy

	validates_presence_of :name, :value

  def self.with_name_like(name)
    find(:all, :order => "name asc", :conditions => ["name like ?", "%#{name}%"])
  end

  def add_bucket=(bucket_id)
    setting_usages.build(:bucket_id => bucket_id)
  end

  def ordered_setting_overrides
    setting_overrides.sort { |x,y| x.priority <=> y.priority }
  end

  def context
    Array.new(Axis.count).collect { "*" }.join(".")
  end

  def remove_from!(bucket)
    return unless buckets.include?(bucket)
    setting_usages.each do |su|
      su.destroy if su.bucket == bucket
      return
    end
  end

  def priority
    return 0
  end

  def resolve_for(axes)
    result = self
    setting_overrides.each do |so|
      if so.satisfies(axes)
        result = so if so.priority > result.priority
      end
    end
    return result
  end

end
